import { View, Button, Picker, Textarea } from '@tarojs/components'
import { useState } from 'react'
import Taro from '@tarojs/taro'
import './index.scss'

// 代码类型选项
const CODE_TYPES = [
  { label: 'JavaScript', value: 'javascript' },
  { label: 'Java', value: 'java' }
]

const Beauty = () => {
  // 状态管理
  const [code, setCode] = useState('') // 用户输入的代码
  const [codeType, setCodeType] = useState('javascript') // 代码类型
  const [isLoading, setIsLoading] = useState(false) // 加载状态

  // 处理代码类型选择
  const handleTypeChange = (e) => {
    setCodeType(CODE_TYPES[e.detail.value].value)
  }

  // 处理代码输入
  const handleCodeChange = (e) => {
    setCode(e.detail.value)
  }

  // 处理代码美化
  const handleBeautify = async () => {
    if (!code.trim()) {
      Taro.showToast({
        title: '请输入需要美化的代码',
        icon: 'none'
      })
      return
    }

    setIsLoading(true)
    try {
      // 调用后端接口进行代码美化
      const res = await Taro.request({
        url: 'http://43.143.236.218:8088/format', 
        method: 'POST',
        data: {
          code,
          type: codeType
        }
      })

      if (res.data && res.data.code) {
        setCode(res.data.code)
        Taro.showToast({
          title: '美化成功',
          icon: 'success'
        })
      } else {
        throw new Error('美化失败')
      }
    } catch (error) {
      Taro.showToast({
        title: error.message || '美化失败，请重试',
        icon: 'none'
      })
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <View className='beauty-container'>
      <View className='beauty-header'>
        <Picker
          mode='selector'
          range={CODE_TYPES}
          rangeKey='label'
          onChange={handleTypeChange}
          className='beauty-type-picker'
        >
          <View className='beauty-picker'>
            当前选择：{CODE_TYPES.find(type => type.value === codeType)?.label}
          </View>
        </Picker>
        <Button
          className='beauty-btn'
          onClick={handleBeautify}
          loading={isLoading}
        >
          美化
        </Button>
      </View>
      <Textarea
        className='beauty-code-input'
        value={code}
        onInput={handleCodeChange}
        placeholder='请输入需要美化的代码'
      />
    </View>
  )
}

export default Beauty
